package controllers

import (
	"fmt"
	"net/http"
	"strings"

	"github.com/gin-gonic/gin"
	"github.com/your_username/backend-login-system/models"
	"github.com/your_username/backend-login-system/utils"
	"gorm.io/gorm"
)

// Login 处理用户登录请求
func Login(c *gin.Context) {
	type LoginInput struct {
		Username string `form:"username" json:"username" binding:"required"`
		Password string `form:"password" json:"password" binding:"required"`
	}
	var input LoginInput
	if err := c.ShouldBind(&input); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	var user models.User
	if err := globalDB.Where("username =?", input.Username).First(&user).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			c.JSON(http.StatusUnauthorized, gin.H{"error": "用户名不存在"})
		} else {
			c.JSON(http.StatusInternalServerError, gin.H{"error": "数据库查询出错"})
		}
		return
	}

	if !utils.CheckPassword(input.Password, user.Password) {
		c.JSON(http.StatusUnauthorized, gin.H{"error": "密码错误"})
		return
	}

	token, err := utils.GenerateJWT(user.Username)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "生成token出错"})
		return
	}

	userID := user.ID
	c.Header("X-User-ID", fmt.Sprintf("%d", userID))
	c.JSON(http.StatusOK, gin.H{"token": token})
}

// Register 处理用户注册请求
func Register(c *gin.Context) {
	type RegisterInput struct {
		Username string `form:"username" json:"username" binding:"required"`
		Password string `form:"password" json:"password" binding:"required"`
	}
	var input RegisterInput
	if err := c.ShouldBind(&input); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	hashedPassword, err := utils.HashPassword(input.Password)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "密码加密出错"})
		return
	}

	newUser := models.User{
		Username: input.Username,
		Password: hashedPassword,
	}

	if err := globalDB.Create(&newUser).Error; err != nil {
		if strings.Contains(err.Error(), "Duplicate entry") {
			c.JSON(http.StatusConflict, gin.H{"error": "用户名已存在"})
		} else {
			c.JSON(http.StatusInternalServerError, gin.H{"error": "注册用户到数据库出错"})
		}
		return
	}

	c.JSON(http.StatusCreated, gin.H{"message": "注册成功"})
}
